package org.osami.appevent;

import java.util.Hashtable;

import org.json.JSONObject;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;

import android.content.Context;
import android.content.Intent;

public class OSGi2IntentHandler implements EventHandler {
	
	Context androidContext;
	String intentID;
	
	protected Logger log;
	public OSGi2IntentHandler(Context androidContext, String intentID )
	{
		this.androidContext = androidContext;
		this.intentID = intentID;
		
		this.log = new Logger(this.getClass().getName());
	}
		
	@Deprecated
	protected String eventToJSONString(Event event)
	{
		String[] osgi_properties = event.getPropertyNames();
		
		Hashtable<String, String> jsonDict = new Hashtable<String,String>();
		
		for (int j = 0; j < osgi_properties.length; j++) {
			jsonDict.put(osgi_properties[j], event.getProperty(osgi_properties[j]).toString());
		}
		
		JSONObject json = new JSONObject(jsonDict);
		return json.toString();
	}
	
	/** Converts OSGi event to Android intent */
	public void handleEvent(Event event) {
		
		this.log.df("Converting OSGi topic %s to android Intent %s", event.getTopic(), intentID);
		
		// TODO: Have the osgi event type on the action?
		
		Intent intent = new Intent();		
		intent.setAction(intentID);
		intent.putExtra("topic", event.getTopic());
		
		Hashtable<String,String> jsondict = new Hashtable<String,String>(); 
		
		String[] osgi_properties = event.getPropertyNames();
		for (int j = 0; j < osgi_properties.length; j++) {
			
			String propName = osgi_properties[j];
			Object prop = event.getProperty(propName);
			
			jsondict.put(propName, prop.toString());
			/*
			if(prop instanceof java.io.Serializable){
				
				intent.putExtra(propName, (java.io.Serializable)prop);
			}
			else{
				intent.putExtra(propName, prop.toString());
			}
			*/
		}
		intent.putExtra("json", new JSONObject(jsondict).toString());
		this.androidContext.sendBroadcast(intent);
	}

}
